package com.humanminoritygame.model;

import java.util.HashSet;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class HibernateUserRepo extends HibernateGenericRepo implements UserRepo {
  
  @Autowired
  public HibernateUserRepo(SessionFactory sessionFactory) {
    setSessionFactory(sessionFactory);
  }

  @Override
  public void addUser(User user) {
    Session session = getSession();
    getSession().save(user);
    session.flush();
  }

  @Override
  public void delUser(User user) {
    getSession().delete(user);
  }

  @Override
  public User getUser(String name, String password) {
    Query q = getSession().createQuery("SELECT u FROM User u WHERE u.name=:uname AND u.password=:upass");
    q.setString("uname",name);
    q.setString("upass",password);
    return (User)q.uniqueResult();
  }

  @Override
  public User getUserByName(String name) {
    Query q = getSession().createQuery("SELECT u FROM User u WHERE u.name =:uname");
    q.setString("uname",name);
    try{
      User user = (User) q.uniqueResult();
      return user;
    }catch(Exception e){
      throw new RuntimeException("Database error: There is more than one user with username = "+ name);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public SortedSet<User> getUsers() {
    SortedSet<User> users = new TreeSet<User>();  
    users.addAll(getSession().createQuery("SELECT u FROM User u").list());
    return users;
  }

  @SuppressWarnings("unchecked")
  @Override
  public Set<User> getRobots() {
    Query q = getSession().createQuery("SELECT u FROM User u WHERE u.robot=TRUE");
    Set<User> users = new HashSet<User>();
    users.addAll(q.list());
    if(users.isEmpty()){
      return null;
    }
    return users;
  }

  @Override
  public User getUserById(Long userId) {
    return (User)getSession().get(User.class, userId);
  }

  @SuppressWarnings("unchecked")
  @Override
  public SortedSet<User> getHumanUsers() {
    SortedSet<User> users = new TreeSet<User>();  
    users.addAll(getSession().createQuery("SELECT u FROM User u WHERE u.robot = false").list());
    return users;
  }
}
